package cn.utils;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static Configuration configuration;
    private final static SessionFactory sessionFactory;

    static {
        try {
            configuration = new Configuration().configure();
            sessionFactory = configuration.buildSessionFactory();
        } catch (HibernateException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
           throw new ExceptionInInitializerError(e);
        }
    }

    private HibernateUtil(){

    }

    public static Session currentSession(){
        return  sessionFactory.getCurrentSession();
    }

    public  static void commit(Transaction tx){
        if (tx!=null){
            tx.commit();
        }
    }

    public  static void rollback(Transaction tx){
        if (tx!=null){
            tx.rollback();
        }
    }

    public  static Transaction getTransaction(Session session){
        if (session!=null){
            return  session.beginTransaction();
        }
        return null;
    }

}
